function getShoppingCart(){
    var cart = false;
    if(sessionStorage.getItem("cart"))
        cart = JSON.parse(sessionStorage.getItem("cart"));
    else{
        cart = new Array();
        updateShoppingCart(cart);
    }
    return cart;
}

function updateShoppingCart(cart){
    sessionStorage.setItem("cart", JSON.stringify(cart));
}

function addItemToCart(productId, price){
    var cart = getShoppingCart();
    var exist = false;
    for (var i = 0; i < cart.length; i++) {
        var item = cart[i];
        if(item.productId != productId)
            continue;
        
        item.quantity = item.quantity + 1;
        cart[i] = item;
        exist = true;
        break;
    }
    if(exist){
        updateShoppingCart(cart);
        return false;
    }
    
    var newItem = new CartItem(productId, 1, price);
    cart[cart.length] = newItem;
    updateShoppingCart(cart);
    return false;
}

function getCurrentUser(){
    var user = false;
    if(sessionStorage.getItem("user")){
        user = sessionStorage.getItem("user");
    }
    return user;
}

function getCartItemsQuantity(){
    var cart = getShoppingCart();
    return cart.length;
}

function getCartTotal(){
    var cart = getShoppingCart();
    var total = 0;
    for (var i = 0; i < cart.length; i++) {
        var item =  cart[i];
        total += item.price * item.quantity;
    }
    return total;
}
